package com.weirblog.resource;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.commons.lang3.StringUtils;

import com.weirblog.entity.Posts;

import io.quarkus.hibernate.reactive.panache.Panache;
import io.smallrye.mutiny.Uni;
import io.vertx.core.json.JsonObject;

@Path("article")
@ApplicationScoped
public class ArticleResource {

	@POST
	@Path("add")
	public Uni<Response> add(Posts posts) {
		String description = posts.description;
		if (StringUtils.isNotBlank(posts.description) && description.length() > 100) {
			description = description.substring(0, 99);
		}
		var desc = description;
		if (posts.id != null) {
			return Panache.withTransaction(() -> Posts.<Posts>findById(posts.id).onItem().ifNotNull().invoke(entity -> {
				entity.postTitle = posts.postTitle;
				entity.types = posts.types;
				entity.description = desc;
				entity.content = posts.content;
				entity.postPic = posts.postPic;
			})).onItem().ifNotNull()
					.transform(entity -> Response.ok(new JsonObject().put("msg", "修改成功").put("success", true)).build())
					.onItem().ifNull().continueWith(Response.ok().status(Status.NOT_FOUND)::build);
		}
		posts.description = description;
		return Panache.withTransaction(posts::persist).replaceWith(
				Response.ok(new JsonObject().put("msg", "新增成功").put("success", true)).status(Status.CREATED)::build);
	}
}
